package MyJson;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * Created by yangluhua on 2016/8/20 0020.
 */
public class JsonUtil implements YSON{

    @Override
    public <T> String parse(T t) {
        try {
            Class clazz = t.getClass();
            Field[] fields = clazz.getDeclaredFields();
            Field.setAccessible(fields,true);
            StringBuilder sb = new StringBuilder("{");
            for(Field field : fields){
                String fieldName = field.getName();
                Object fieldValue = field.get(t);
                if(fieldValue instanceof String){
                    sb.append("\""+fieldName+"\":\""+fieldValue+"\",");
                }else {
                    sb.append("\""+fieldName+"\":"+fieldValue+",");
                }
            }

            Method[] methods = clazz.getMethods();
            for(Method method:methods){
                String methodName = method.getName();
                if(methodName.startsWith("get")){
                    Object value = method.invoke(t);
                    if(value instanceof String){
                        sb.append("\""+methodName.substring(3)+"\":\""+value+"\",");
                    }else {
                        sb.append("\""+methodName.substring(3)+"\":"+value+",");
                    }
                }
            }

            for (Field field : fields) {
                if (field.isAnnotationPresent(Name.class)) {
                    Annotation[] annotations = field.getDeclaredAnnotations();
                    for (Annotation annotation : annotations) {
                        if (annotation instanceof Name) {
                            Name name = (Name) annotation;
                            System.out.println(name.value());
                        }
                    }
                }
              /*  String fieldName = field.getName();
                Object fieldValue = field.get(t);
                if(fieldValue instanceof String){
                    sb.append("\""+fieldName+"\":\""+fieldValue + "\",");
                }else {
                    sb.append("\""+fieldName+"\":"+fieldValue+",");
                }*/
            }

          /*  String s = sb.substring(0,sb.length()-1)+"}";
            System.out.println(s);*/
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    //首字母转大写
    public  String toUpperCaseFirstOne(String s)
    {
        if(Character.isUpperCase(s.charAt(0)))
            return s;
        else
            return (new StringBuilder()).append(Character.toUpperCase(s.charAt(0))).append(s.substring(1)).toString();
    }

}
